import { createApp } from "./main";

export default async ctx => {
  const { App, store, router } = createApp()

  router.push(ctx.url)
  await new Promise(
    (resolve, reject) => router.onReady(resolve, reject)
  )

  const matchedComponents = router.getMatchedComponents()
  if (!matchedComponents.length) {
    throw 'No resources'
  }

  const asyncQueue = []
  for (const component of matchedComponents) {
    if (component.asyncData) {
      asyncQueue.push(
        component.asyncData({
          store,
          route: router.currentRoute
        })
      )
    }
  }

  await Promise.all(asyncQueue)

  // 注入上下文 将保存到前端的__INITIAL_STATE__
  ctx.state = store.state

  return App
}